﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class DropDownExtent : Dropdown
{
    public bool AlwaysCallback = false;//是否开启 点击选项按钮总是回调

    private float ScrollbarValue = -1f;
    private Scrollbar Scrollbar;

    public void Show()
    {
        base.Show();
        Transform toggleRoot = this.transform.Find("Dropdown List/Viewport/Content");
        this.Scrollbar = this.transform.Find("Dropdown List/Scrollbar").GetComponent<Scrollbar>();

        if (this.ScrollbarValue != -1f)
        {
            this.Scrollbar.value = this.ScrollbarValue;
        }

        Toggle[] toggleList = toggleRoot.GetComponentsInChildren<Toggle>(false);
        for (int i = 0; i < toggleList.Length; i++)
        {
            Toggle temp = toggleList[i];
            temp.onValueChanged.RemoveAllListeners();
            temp.isOn = false;
            temp.onValueChanged.AddListener(x => this.OnSelectItemEx(temp));
        }

        this.Scrollbar.onValueChanged.AddListener((scValue) => { this.ScrollbarValue = scValue; });
    }

    public override void OnPointerClick(PointerEventData eventData)
    {
        this.Show();
    }

    public void OnSelectItemEx(Toggle toggle)
    {
        if (!toggle.isOn)
        {
            toggle.isOn = true;
            return;
        }

        int selectedIndex = -1;
        Transform tr = toggle.transform;
        Transform parent = tr.parent;
        for (int i = 0; i < parent.childCount; i++)
        {
            if (parent.GetChild(i) == tr)
            {
                selectedIndex = i - 1;
                break;
            }
        }

        if (selectedIndex < 0)
        {
            return;
        }
        if (this.value == selectedIndex && this.AlwaysCallback)
        {
            this.onValueChanged.Invoke(this.value);
        }
        else
        {
            this.value = selectedIndex;
        }

        this.Hide();
    }
}
